package com.xexun.gpstracker.ui;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.lurencun.service.autoupdate.Version;
import com.lurencun.service.autoupdate.internal.NetworkUtil;
import com.lurencun.service.autoupdate.internal.VersionDialogListener;
import com.xexun.gpstracker.AppContext;
import com.xexun.gpstracker.AppManager;
import com.xexun.gpstracker.MainActivity;
import com.xexun.gpstracker.channel.R;
import com.xexun.gpstracker.common.Constants;
import com.xexun.gpstracker.common.MyConstants;
import com.xexun.gpstracker.dialog.NoWifiDialog;
import com.xexun.gpstracker.dialog.WizardAlertDialog;
import com.xexun.gpstracker.fix.grant.PermissionsManager;
import com.xexun.gpstracker.fix.grant.PermissionsResultAction;
import com.xexun.gpstracker.inter.HttpCallback;
import com.xexun.gpstracker.my.activity.SettingActivity;
import com.xexun.gpstracker.pojo.ResponseData;
import com.xexun.gpstracker.pojo.User;
import com.xexun.gpstracker.update.UpdateManager;
import com.xexun.gpstracker.util.*;
import com.xexun.gpstracker.vo.FlavorType;
import com.xexun.gpstracker.vo.Session;
import org.xutils.http.annotation.HttpResponse;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import static android.content.ContentValues.TAG;

/**
 * 用户登录页面
 *
 * @author huangfei
 */
public class LoginActivity extends Activity {

    private SharedPreferences mSharedPreferences;
    //    private AppUpdate mAppUpdate;
    private EditText pwdText;
    private EditText phoneText;
    private Button registButton, loginButton;
    private TextView forgotPwdView, versionTV;
    private CheckBox checkBox;    //记住密码
    private int count;
    private long lastTime;
    private UpdateManager mUpdateManager;

    public static String LoginInfo = "loginInfo";
    public static String LoginOther = "loginOther";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        String loginStr = intent.getStringExtra(LoginInfo);
        if (loginStr != null&& loginStr.equals(LoginOther)){
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(R.string.confirm_logout_offline_txt);
            builder.setTitle(R.string.msg_notify);
            builder.setCancelable(false);
            builder.setPositiveButton(R.string.known, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();

                }
            });
            AlertDialog dialog = builder.create();
            dialog.show();
        }

        Log.i(Constants.TAG, "启动登录界面");
        mSharedPreferences = Utils.getPreferences(LoginActivity.this);
        setContentView(R.layout.activity_login);// 显示真正的应用界面

       Constants.baseUrl = Utils.getBaseUrl(this);
//        Constants.baseUrl = "http://192.168.1.189:8080/";

        //初始化缓存环境
        Session.getInstance().clearData();

        try {
            versionTV = (TextView) findViewById(R.id.verTv);
            versionTV.setText(getString(R.string.version_tit) + Constants.versionName);
            versionTV.setOnClickListener(clickListener);
        } catch (Exception e) {
            e.printStackTrace();
        }
        initView();

        initEvents();

        getVersion();
        deleteExceptionLog();

        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(LoginActivity.this,
                new String[]{Manifest.permission.CALL_PHONE, Manifest.permission.READ_PHONE_STATE},
                new PermissionsResultAction() {
                    @Override
                    public void onGranted() {
                        initExtraData();
                    }

                    @Override
                    public void onDenied(String permission) {
                        CommUtil.showMsgShort(String.format(getString(R.string.permission_refuse_comm_note), getString(R.string.permission_refuse_call_phone_note)));
                    }
                });

        //if(savedInstanceState != null) {
        /*    Intent intent = getIntent();
            String data = intent.getStringExtra("itemData");
                    //intent.getExtras().getString("itemData");

            if (!CommUtil.isBlank(data) && data.startsWith("powneron")) {
                Toast.makeText(this, "powneron data", Toast.LENGTH_LONG).show();
                final String savedPhone = mSharedPreferences.getString(MyConstants.USER_PHONE, "");
                final String savedPsd = mSharedPreferences.getString(MyConstants.USER_PWD, "");
                if(!CommUtil.isBlank(savedPhone) && !CommUtil.isBlank(savedPsd)) {
                    checkBox.setChecked(true);
                    PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(LoginActivity.this,
                            new String[]{Manifest.permission.CALL_PHONE, Manifest.permission.READ_PHONE_STATE},
                            new PermissionsResultAction() {
                                @Override
                                public void onGranted() {
                                    if (CommUtil.isBlank(Session.getInstance().getClientId())) {
                                        initExtraData();
                                    }
                                    login(savedPhone, savedPsd);
                                }

                                @Override
                                public void onDenied(String permission) {
                                    CommUtil.showMsgShort(String.format(getString(R.string.permission_refuse_comm_note), getString(R.string.permission_refuse_call_phone_note)));
                                }
                            });
                }
            }*/
       // }
    }

    public void initExtraData() {
        List<String> imeis = IMEI.getIMEI(LoginActivity.this);
        if (CommUtil.isNotEmpty(imeis)) {
            Session.getInstance().setClientId(imeis.get(0));
        }
    }

    private void initEvents() {
        if (Constants.FLAVOR != FlavorType.OLDGPS) {
//            phoneText.addTextChangedListener(new PrettyTextChangeListener(3, 4));
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
    }

    /**
     * 删除异常记录
     */
    private void deleteExceptionLog() {
        boolean aBoolean = mSharedPreferences.getBoolean(MyConstants.EXCEPTION_LOG_UPLOAD, false);
        if (aBoolean) {
            File file = new File(Utils.getAvailableStoragePath() + "crashLog/");
            if (!file.exists()) {
                Log.d("TAG", "异常捕获存储目录不存在");
                return;
            }

            File[] files = file.listFiles();
            if (files != null) {
                for (File mFile : files) {
                    if (!mFile.isDirectory()) {
                        //删除数据
                        mFile.delete();
                        Log.d("TAG", "异常捕获存_删除数据");
                    }
                }
            }
        }
    }

    private void initView() {
        phoneText = (EditText) findViewById(R.id.phoneET);
        pwdText = (EditText) findViewById(R.id.pwdET);
        registButton = (Button) findViewById(R.id.registBtn);
        loginButton = (Button) findViewById(R.id.loginBtn);
        forgotPwdView = (TextView) findViewById(R.id.forgotPwdTV);
        checkBox = (CheckBox) findViewById(R.id.pwdCB);
        if (Constants.IS_CHINA_VERSION) {
            ImageView imageView = (ImageView) findViewById(R.id.logoIV);
            imageView.setImageResource(R.drawable.ic_launcher);
        }

        if (mSharedPreferences.getBoolean(MyConstants.REMEMBER_PWD, false)) {
            String savedPhone = mSharedPreferences.getString(MyConstants.USER_PHONE, "");
            if (Constants.FLAVOR == FlavorType.OLDGPS) {
                phoneText.setText(savedPhone);
            } else {
//                phoneText.setText(CommUtil.prettyString(savedPhone, null, true, 3, 4));
                  phoneText.setText(savedPhone);
            }
            pwdText.setText(mSharedPreferences.getString(MyConstants.USER_PWD, ""));
            checkBox.setChecked(true);
        } else {
            checkBox.setChecked(false);
        }

        registButton.setOnClickListener(clickListener);
        loginButton.setOnClickListener(clickListener);
        forgotPwdView.setOnClickListener(clickListener);

        Constants.hasNewVersion = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Session.getInstance().getMainActivity() != null) {
            LoginActivity.this.finish();
        }
        AppContext.forceLogout = false;
    }

    @Override
    protected void onPause() {
        super.onPause();
//        if (mAppUpdate != null) {
//            mAppUpdate.callOnPause();
//        }
    }


    private OnClickListener clickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.loginBtn:
                    String pTxt = phoneText.getText().toString().trim();
                    final String account = Constants.FLAVOR == FlavorType.OLDGPS ? pTxt : CommUtil.trimSeprator(pTxt, null);
                    if (CommUtil.isBlank(account)) {
                        Toast.makeText(LoginActivity.this, R.string.phone_null_err, Toast.LENGTH_SHORT).show();
                    } else if (CommUtil.isBlank(pwdText.getText().toString())) {
                        Toast.makeText(LoginActivity.this, R.string.pwd_null_err, Toast.LENGTH_SHORT).show();
                    } else {
                        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(LoginActivity.this,
                                new String[]{Manifest.permission.CALL_PHONE, Manifest.permission.READ_PHONE_STATE},
                                new PermissionsResultAction() {
                                    @Override
                                    public void onGranted() {
                                        if (CommUtil.isBlank(Session.getInstance().getClientId())) {
                                            initExtraData();
                                        }
                                        login(account, pwdText.getText().toString().trim());
                                    }

                                    @Override
                                    public void onDenied(String permission) {
                                        CommUtil.showMsgShort(String.format(getString(R.string.permission_refuse_comm_note), getString(R.string.permission_refuse_call_phone_note)));
                                    }
                                });
                    }
//				Intent loginIntent = new Intent(LoginActivity.this, MainActivity.class);
//				LoginActivity.this.startActivity(loginIntent);
                    break;
                case R.id.registBtn:
                    Intent registIntent = new Intent(LoginActivity.this, RegistActivity.class);
                    LoginActivity.this.startActivity(registIntent);
                    Session.getInstance().setLoginActivity(LoginActivity.this);
                    break;
                case R.id.forgotPwdTV:
                    Intent pwdIntent = new Intent(LoginActivity.this, FindPwdActivity.class);
                    LoginActivity.this.startActivity(pwdIntent);
                    break;
                case R.id.verTv:
                    if (count >= 7) {
                        Intent intent = new Intent(LoginActivity.this, SettingActivity.class);
                        startActivity(intent);
                        lastTime = 0;
                        count = 0;
                    } else if (lastTime == 0 || System.currentTimeMillis() - lastTime < 1500) {
                        lastTime = System.currentTimeMillis();
                        count++;
                    } else {
                        lastTime = 0;
                        count = 0;
                    }
            }
        }
    };

    /**
     * 用户登录
     *
     * @param phone
     * @param pwd
     */
    private void login(final String phone, final String pwd) {
        User.login(this, phone, pwd, new HttpCallback() {
            @Override
            public void onStart() {
                WizardAlertDialog.getInstance().showProgressDialog(R.string.login_post_data, LoginActivity.this);
            }

            @Override
            public void onFinish() {

            }

            @Override
            public void onSuccess(ResponseData obj) {
                WizardAlertDialog.getInstance().closeProgressDialog();
                if (obj.getRetcode() == 1) {
                    if (checkBox.isChecked()) {
                        long user_id = JSONHelper.getLong(obj.getBody(), "userId");
                        Editor editor = mSharedPreferences.edit();
                        editor.putString(MyConstants.USER_PHONE, phone);
                        editor.putString(MyConstants.USER_PWD, pwd);
                        editor.putLong(MyConstants.USER_ID, user_id);
                        editor.putBoolean(MyConstants.REMEMBER_PWD, true);
                        editor.apply();
                    } else {
                        Editor editor = mSharedPreferences.edit();
                        editor.putString(MyConstants.USER_PHONE, "");
                        editor.putString(MyConstants.USER_PWD, "");
                        editor.putLong(MyConstants.USER_ID, 0);
                        editor.putBoolean(MyConstants.REMEMBER_PWD, false);
                        editor.apply();
                    }
                            /*------------*/
                    //Session.getInstance().setAccessKey(JSONHelper.getString(obj.getBody(), "accesskey"));
                    Session.getInstance().setAccessKey(JSONHelper.getString(obj.getBody(), "accesskey"));
                    User user = new User();
                    user.setId(JSONHelper.getLong(obj.getBody(), "id"));
                    user.setPhone(phone);
                    user.setAppUserNum(JSONHelper.getString(obj.getBody(), "appUserNum"));
                    user.setImei(obj.getBodyString("imei"));
                    Session.getInstance().setUser(user);
                    Session.getInstance().setImei(user.getImei());

                    AppContext.termType = JSONHelper.getInt(obj.getBody(), "type");

                    Intent loginIntent = new Intent(LoginActivity.this, MainActivity.class);
                    LoginActivity.this.startActivity(loginIntent);
                    AppContext.isEntered = true;
                    //LoginActivity.this.finish();
                } else if (CommUtil.isNotBlank(obj.getMsg())) {
                    Toast.makeText(LoginActivity.this, obj.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(String message) {
                WizardAlertDialog.getInstance().closeProgressDialog();
                Toast.makeText(LoginActivity.this, R.string.login_err, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
                Utils.getManager(LoginActivity.this).hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

//        if (!AppContext.isEntered) {
//            Intent itt = new Intent(AppContext.getContext(), CommunicationService.class);
//            LoginActivity.this.stopService(itt);

//        Intent pushIntent = new Intent(AppContext.getContext(), PushService.class);
//        LoginActivity.this.stopService(pushIntent);

//        }
    }


    /**
     * 获取终端版本信息
     */
    private void getVersion() {

        //这里来检测版本是否需要更新

        try {
            mUpdateManager = new UpdateManager(this);
            mUpdateManager.checkUpdateInfo(this);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

    /*
        User.getAppVersion(this, false, new CommCallback() {
            @Override
            public void execute(Object object) {
                final Version version = (Version) object;
                if (version == null) {
                    return;
                }
                if(Constants.FLAVOR  == FlavorType.PHONELOC) {
                    checkNetworkAndUpdate(version);
                    return;
                }
                Constants.hasNewVersion = true;
                FoundVersionDialog dialog = new FoundVersionDialog(LoginActivity.this, version, new VersionDialogListener() {
                    @Override
                    public void doUpdate(boolean laterOnWifi) {
                        if (!laterOnWifi) {
                            checkNetworkAndUpdate(version);
                        } else {
                            new VersionPersistent(LoginActivity.this).save(version);
                        }
                    }

                    @Override
                    public void doIgnore() {
                        if (version.forceUpdate) {
                            onBackPressed();
                        }
                    }
                });
                dialog.show();
            }
        });
        */
    }



//    private void checkNetworkAndUpdate(final Version version) {
//        if (NetworkUtil.getNetworkType(LoginActivity.this) == NetworkUtil.WIFI) {
//            Log.d(Constants.TAG, "现在是wifi网络");
//            AppUpdataHandle.getInstance(LoginActivity.this).downloadAndInstall(version);
//        } else if (NetworkUtil.getNetworkType(LoginActivity.this) == NetworkUtil.MOBILE) {
//            Log.d(Constants.TAG, "现在走的是流量");
//            NoWifiDialog dialog = new NoWifiDialog(LoginActivity.this, version, new VersionDialogListener() {
//                @Override
//                public void doUpdate(boolean laterOnWifi) {
//                    AppUpdataHandle.getInstance(LoginActivity.this).downloadAndInstall(version);
//                }
//
//                @Override
//                public void doIgnore() {
//                }
//            });
//            dialog.show();
//
//        } else {
//            Toast.makeText(LoginActivity.this, "请检查网络是否连接", Toast.LENGTH_SHORT).show();
//        }
//    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if(Constants.FLAVOR  != FlavorType.PHONELOC) {  //退出应用不关闭后台服务
            AppManager.getAppManager().AppExit();
        }
    }
}
